/* Owner.m
 *
 * You may freely copy, distribute, and reuse the code in this example.
 * NeXT disclaims any warranty of any kind, expressed or  implied, as to its
 * fitness for any particular use.
 *
 * 
 *
 */


#import <eointerface/eointerface.h>
#import "Owner.h"
#import "NSAuthor.h"

#define ARCHIVE_FILE @"NSObjectArchive"

@implementation Owner

 
- appDidInit:sender
{
    EOAdaptorChannel	*adaptorChannel;
    
    // Set up the adaptor channel for debugging
    adaptorChannel = [[dataSource databaseChannel] adaptorChannel]; 
    [(EOAdaptorChannel *)adaptorChannel setDelegate: self];
    return self;
}

    
- (void)adaptorChannel:channel didEvaluateExpression:(NSString *)expression
{
    NSLog (expression);
}


- writeObject:sender
{
    eoArray = [controller selectedObjects];
    // Archive the first object in the array of selected objects.
    //  In this example, only one object is selected at a time.
	if ([eoArray count] == 0) {
		NXRunAlertPanel(NULL, "No object to archive!", NULL, NULL, NULL);
		return self;
		}
    eoAuthor = [eoArray objectAtIndex:0];
    
    [self archiveThisNSObject:eoAuthor]; 
    
    return self;
}

- readObject:sender
{
    eoAuthor = (NSAuthor *)[self unarchiveNSObject];
    return self;
}


- (BOOL) archiveThisNSObject:(NSObject *)nsobject
{
    BOOL	b;
    NSString *archivePath;
    
    if (!nsobject)
	return NO;
    
	
    archivePath = [NSString stringWithFormat:@"%@/%@", [self applicationPath], ARCHIVE_FILE];
    b = [NSArchiver archiveRootObject:nsobject toFile:archivePath];
    if (b == YES)
	[textObject appendText:"NSObject archiving succeeded\n"];
    else
    	[textObject appendText:"NSObject archiving failed\n"];
	
    return b;
}

- (NSObject *) unarchiveNSObject 
{
    NSObject *nsobject;
    char 	buf[1024];
    NSString *archivePath;
	
    archivePath = [NSString stringWithFormat:@"%@/%@", [self applicationPath], ARCHIVE_FILE];

    nsobject = [NSUnarchiver unarchiveObjectWithFile:archivePath];
    if (nsobject) {
	[textObject appendText:"NSObject unarchiving succeeded\n"];
	sprintf(buf, "%s\n",[[(NSAuthor *)nsobject description] cString]);
	[textObject appendText: "Author contents:"];
	[textObject appendText:buf];
    }
    else
	[textObject appendText:"NSObject unarchiving failed\n"];

    return nsobject;
}

- (NSString *)applicationPath 
{
    int           i;
    NSString   *appPathName = nil;

    for (i = strlen(NXArgv[0]) - 1; (i >= 0) && (NXArgv[0][i] != '/'); i--);
    appPathName = [NSString stringWithCString:NXArgv[0] length:i];
    if (NXArgv[0][0] != '/') {
	char path[MAXPATHLEN+1];
	appPathName = [NSString stringWithFormat:@"%s/%@", getwd(path), appPathName];
    }
    return appPathName;
}


@end


@implementation Text(printResults)

- appendText:(const char *)newText
{
    int currentLength = [self textLength];

    [self setSel:currentLength :currentLength];
    [self replaceSel:newText];
    [self scrollSelToVisible];
    return self;
}

@end
